# -*- coding: utf-8 -*-
# @Time : 2022/4/21 18:28
# @Author : Yinkay·Huang
# @File : text.py
import csv
import numpy as np
import os
from collections import Counter
from wordcloud import WordCloud, ImageColorGenerator
from PIL import Image
import math
import re
import snownlp
import jieba
import jieba.analyse
import matplotlib.pyplot as plt
from pyecharts.charts import Map
from pyecharts import options as opts

plt.rcParams['font.sans-serif'] = ['SimHei']  # 绘图时可以显示中文
plt.rcParams['axes.unicode_minus'] = False  # 绘图时可以显示中文

path = "我的微信好友信息.csv"


# 性别分析
def fun_analyse_sex(path):
    # 读取文件性别数据
    with open(path) as f:
        reader = csv.reader(f)
        column = []
        name = []
        for row in reader:
            column.append(row[4])
            name.append(row[2])
    sexs = list(column[1:])  # 收集性别数据
    counts = list(map(lambda x: x[1], Counter(sexs).items()))  # 统计不同性别的数量
    counts = sorted(counts)
    labels = ['保密', '男', '女']  # 2:女，1：男，0：保密
    colors = ['red', 'yellow', 'blue']
    plt.figure(figsize=(20, 8), dpi=80)
    plt.axes(aspect=1)
    plt.pie(counts,  # 性别统计结果
            labels=labels,  # 性别展示标签
            colors=colors,  # 饼图区域配色
            labeldistance=1.1,  # 标签距离圆点距离
            autopct='%3.1f%%',  # 饼图区域文本格式
            shadow=False,  # 饼图是否显示阴影
            startangle=90,  # 饼图起始角度
            pctdistance=0.6  # 饼图区域文本距离圆点距离
            )
    plt.legend(loc='upper left')  # 标签位置
    plt.title(name[1] + '的微信好友性别比例')
    plt.show()


# 头像拼接
def all_head_images():
    # 把所以好友头像生成一张图片
    x = 0
    y = 0
    images = os.listdir("HeadImages")  # 返回指定的文件夹包含的文件或文件夹的名字的列表。
    print(len(images))
    new_image = Image.new('RGBA', (640, 640))  # new一个新的图像
    line_num = int(math.sqrt(len(images)))  # 计算位置
    width = int(640 / line_num)
    # 开始拼图
    for i in images:
        image = Image.open('HeadImages/' + i)
        image = image.resize((width, width))
        new_image.paste(image, (x * width, y * width))
        x += 1
        if x == line_num:
            x = 0
            y += 1
    # 输出
    new_image.save('all.png')


# 签名分析
def fun_analyse_Signature(path):
    # 个性签名分析
    signatures = ''
    emotions = []
    # 提取签名数据
    with open(path) as f:
        reader = csv.reader(f)
        column = []
        name = []
        for row in reader:
            column.append(row[5])
            name.append(row[2])
        friends = list(column)
        for signature in friends:
            if signature != None:
                signature = signature.strip().replace("span", "").replace("class", "").replace("emoji", "")  # 去除无关数据
                signature = re.sub(r'1f(\d.+)', "", signature)
            if len(signature) > 0:
                nlp = snownlp.SnowNLP(signature)
                emotions.append(nlp.sentiments)  # nlp.sentiments：权值
                signatures += " ".join(jieba.analyse.extract_tags(signature, 5))  # 关键字提取
    back_coloring = np.array(Image.open("weixin.png"))  # 图片可替换
    word_cloud2 = WordCloud(font_path='simkai.ttf',
                            background_color='white',
                            max_words=1200,
                            mask=back_coloring,
                            margin=15)
    word_cloud2.generate(signatures)
    image_colors = ImageColorGenerator(back_coloring)
    plt.figure(figsize=(20, 8), dpi=160)
    plt.imshow(word_cloud2.recolor(color_func=image_colors))
    plt.axis("off")
    plt.show()
    word_cloud2.to_file("signatures.jpg")
    # 文本分析，生活态度
    count_positive = len(list(filter(lambda x: x > 0.66, emotions)))  # 大于0.66为积极
    count_negative = len(list(filter(lambda x: x < 0.33, emotions)))  # 小于0.33为消极
    count_neutral = len(list(filter(lambda x: 0.33 <= x <= 0.66, emotions)))
    labels = [u'积极', u'中性', u'消极']
    values = (count_positive, count_neutral, count_negative)
    plt.rcParams['font.sans-serif'] = ['simHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.xlabel("情感判断")
    plt.ylabel("频数")
    plt.xticks(range(3), labels)
    plt.legend(loc='upper right')
    plt.bar(range(3), values, color='lightskyblue')
    plt.title(name[1] + '的微信好友签名信息情感分析情况')
    plt.show()


# 可视化城市
def theMap(path):
    # 提取城市数据
    with open(path) as f:
        reader = csv.reader(f)
        counts = {}
        name = []
        for row in reader:
            if row[1] in counts.keys():
                counts[row[1]] += 1
            else:
                counts[row[1]] = 1
            name.append(row[2])
    city = [(i, counts[i]) for i in counts.keys()]
    # 配置城市地图
    china_city = (
        Map()
            .add(
            "",
            city[1:],  # 导入数据
            "china-cities",  # 选用城市地图
            label_opts=opts.LabelOpts(is_show=True, font_size=5),  # 设置城市名字字体信息
        )
            .set_global_opts(
            title_opts=opts.TitleOpts(title=name[1] + "的微信好友地图"),
            # 设置热力度
            visualmap_opts=opts.VisualMapOpts(
                min_=0,
                max_=40,
                is_piecewise=True
            ),
        )
            # 输出
            .render("微信好友地图.html")
    )


fun_analyse_sex(path)
all_head_images()
fun_analyse_Signature(path)
theMap(path)
